﻿using System;
using System.Collections.Generic;
using System.Text;

namespace UVMComm
{
    public class PacketHeader
    {
        #region DataMember
        private byte m_CLA;
        private byte m_INS;
        private byte m_L1;
        private byte m_L2;
        private int m_datalength;
        #endregion

        #region DataMemberProperties
        protected byte CLA
        {
            get { return m_CLA; }
            set { m_CLA = value; }
        }
        protected byte INS
        {
            get { return m_INS; }
            set { m_INS = value; }
        }
        protected byte L1
        {
            get { return m_L1; }
            set { m_L1 = value; }
        }
        protected byte L2
        {
            get { return m_L2; }
            set { m_L2 = value; }
        }
        public int DataLength
        {
            get { return m_datalength; }
        }
        #endregion

        #region Constructor
        public PacketHeader(byte[] rhs)
        {
            if (rhs.Length != 4)
                throw new Exception("Header is 4bytes[" + rhs.Length.ToString() + "]");
            CLA = rhs[0];
            INS = rhs[1];
            L1 = rhs[2];
            L2 = rhs[3];
            SetLengthData(L1, L2);
        }
        public PacketHeader(byte cla, byte ins, byte l1, byte l2)
        {
            CLA = cla;
            INS = ins;
            L1 = l1;
            L2 = l2;
            SetLengthData(L1, L2);
        }
        public PacketHeader(byte cla, byte ins, int datasize)
        {
            CLA = cla;
            INS = ins;
            SetLengthData(datasize);
        }
        #endregion

        #region SetLengthDataFunc Called By Constructor
        private void SetLengthData(int datasize)
        {
            if (datasize > 65535)
                throw new Exception("data size is not allow bigger than 65535");

            int L1Section = datasize / 256;
            int L2Section = datasize % 256;

            L1 = Byte.Parse(L1Section.ToString());
            L2 = Byte.Parse(L2Section.ToString());

            m_datalength = datasize;
        }
        private void SetLengthData(byte l1, byte l2)
        {
            int l1int = int.Parse((l1.ToString()));
            int l2int = int.Parse((l2.ToString()));
            m_datalength = l1 * 256 + l2int;
        }
        #endregion

        #region GetDataMemberFunc
        public byte[] GetBytes()
        {
            byte[] retbytes = new byte[4];
            retbytes[0] = CLA;
            retbytes[1] = INS;
            retbytes[2] = L1;
            retbytes[3] = L2;
            return retbytes;
        }
        #endregion
    };
}
